package com.egao.gzh.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.egao.common.core.Constants;
import com.egao.common.core.damon.constant.WechatConstant;
import com.egao.common.core.damon.utils.HttpClientUtil;
import com.egao.common.core.damon.utils.HttpsUtils;
import com.egao.common.core.security.JwtUtil;
import com.egao.common.core.web.BaseController;
import com.egao.common.core.web.JsonResult;
import com.egao.common.system.entity.User;
import com.egao.common.system.service.LoginRecordService;
import com.egao.common.system.service.UserService;
import com.egao.gzh.service.Wxservice;
import com.egao.gzh.utils.AesException;
import com.egao.gzh.utils.WXPublicUtils;
import io.swagger.annotations.ApiOperation;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : Doman
 * @version ：1.0
 * @date : 2020-04-12 17:33
 */
@RestController
@RequestMapping("/api/nt/gzh")
public class GzhController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private LoginRecordService loginRecordService;

    /*
    * 参考下面的网址
    * 网址:https://blog.csdn.net/yhflyl/article/details/85060294
    * */
    @PostMapping("/login")
    @ResponseBody
    public JsonResult user_login(String code, String userHead, String userName, String userGender,
                                 String userCity, String userProvince, HttpServletRequest request) throws Exception {
//        String code2 = request.getParameter("code");
        // 配置请求参数
        Map<String, String> param = new HashMap<>();
        param.put("appid", WechatConstant.WX_LOGIN_APPID);
        param.put("secret", WechatConstant.WX_LOGIN_SECRET);
        param.put("js_code", code);
        param.put("grant_type", WechatConstant.WX_LOGIN_GRANT_TYPE);
        // 发送请求
        String wxResult = HttpClientUtil.doGet(WechatConstant.WX_LOGIN_URL, param);
        JSONObject jsonObject = JSONObject.parseObject(wxResult);

        // 获取参数返回的
        String session_key = jsonObject.get("session_key").toString();
        String open_id = jsonObject.get("openid").toString();
        // 根据返回的user实体类，判断用户是否是新用户，不是的话，更新最新登录时间，是的话，将用户信息存到数据库
        User user = null;
        user = userService.getByXcxopenId(new User(open_id,""));
       if(user != null){
        }else{
            User insert_user = new User();
//            insert_user.setUserHead(userHead);
//            insert_user.setUserName(userName);
//            insert_user.setUserGender(userGender);
//            insert_user.setUserNewLogin(new Date());
//            insert_user.setUserCity(userCity);
//            insert_user.setUserProvince(userProvince);
//            insert_user.setUserOpenid(open_id);
//            System.out.println("insert_user:"+insert_user.toString());
//            // 添加到数据库
//            Boolean flag = userService.insert(insert_user);
//            if(!flag){
//                return JsonResult.error();
//            }
        }
        // 封装返回小程序
        Map<String, String> result = new HashMap<>();
        result.put("session_key", session_key);
        result.put("open_id", open_id);

        String access_token = JwtUtil.buildToken(user.getUsername(), Constants.TOKEN_EXPIRE_TIME, Constants.TOKEN_KEY);
        // 记录登录日志
        loginRecordService.saveAsync(user.getUsername(), request);

        return JsonResult.ok("登录成功").put("session_key", session_key).put("access_token", access_token)
                .put("token_type", JwtUtil.TOKEN_TYPE).put("open_id", open_id);
    }

    /**
     * 微信小程序token
     */
    @ApiOperation(value = "微信公众平台token",notes = "" +
            "signature 公众号加密签名\n" +
            "timestamp 公众号时间戳\n" +
            "nonce 公众号随机数字\n" +
            "echostr 公众号随机字符串\n" +
            "",httpMethod = "GET")
    @GetMapping("/message")
    public String gzhValidate(String signature, String timestamp,
                              String nonce, String echostr) throws AesException {
        //调式url:http://damon.free.idcfengye.com/api/nt/wechart/message
        //正式url:https://godutch.gangcai.store:4332/api/nt/wechart/message
        if (WXPublicUtils.verifyUrl(signature, timestamp, nonce)) {
            System.out.println("公众号验证成功!");
            return echostr;
        }
        return null;
    }

    @PostMapping(value = "message")
    public void processMsg(HttpServletRequest request, HttpServletResponse response) throws IOException, DocumentException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        Wxservice wxservice = new Wxservice();
        // 调用核心服务类接收处理请求
        Map<String, String> requestMap = wxservice.parseRequest(request.getInputStream());
        System.out.println(requestMap);
        //准备回复的数据包
        String resXml = wxservice.getRespose(requestMap);
//                "<xml>" +
//                "<ToUserName><![CDATA["+requestMap.get("FromUserName")+"]]></ToUserName>" +
//                "<FromUserName><![CDATA["+requestMap.get("ToUserName")+"]]></FromUserName>" +
//                "<CreateTime>"+ System.currentTimeMillis()/1000 +"</CreateTime>" +
//                "<MsgType><![CDATA[text]]></MsgType>" +
//                "<Content><![CDATA[why?]]></Content>" +
//                "</xml>";

        PrintWriter out = response.getWriter();
        System.out.println(resXml);
        out.print(resXml);
        out.flush();
        out.close();
//        ServletInputStream is = request.getInputStream();
//        byte[] b = new byte[1024];
//        int len;
//        StringBuilder sb = new StringBuilder();
//        while ((len=is.read(b))!=-1) {
//            sb.append(new String(b, 0, len));
//        }
    }
}